package com.vcredit.creditcat.web;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.vcredit.creditcat.framework.pagination.DefaultCriteria;

/**
 * Controller基类
 * 
 *
 */
public class BaseController{
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String FAIL = "fail";
	private static final String DESC_KEY = "field";
	

	/**
	 * 判断字符串是否为空
	 * @param value
	 * @return
	 */
	protected boolean isEmpty(String value) {
		return value == null || value.trim().length() == 0;
	}
	
	/**
	 * 判断List是否为空
	 * @param list
	 * @return
	 */
	protected boolean isEmpty(List<?> list) {
		return list == null || list.isEmpty();
	}
	
	/**
	 * 从Map获取值，如果NULL则返回空串
	 * @param map
	 * @param key
	 * @return
	 */
	protected Object getValue(Map<String, Object> map, String key) {
		Object obj = map.get(key);
		return obj == null ? "" : obj;
	}
	
	/**
	 * 设置session值
	 * @param request
	 * @param name 会话KEY
	 * @param value 对象值
	 */
	protected void setSessionAttribute(HttpServletRequest request, String name, Object value) {
		request.getSession().setAttribute(name, value);
	}
	
	/**
	 * 获取session值
	 * @param request
	 * @param name 会话KEY
	 * @return 对象值
	 */
	protected Object getSessionAttribute(HttpServletRequest request, String name) {
		return request.getSession().getAttribute(name);
	}
	
	/**
	 * 创建缺省的分页查询条件
	 * @param request
	 * @return 分页查询条件
	 */
	protected DefaultCriteria makeDefaultCriteria(HttpServletRequest request, Object ... keyValues) {
		String paramName = null;
		String paramValue = null;		
		DefaultCriteria dc = new DefaultCriteria(0L, 20L);
		Enumeration<?> paramNames = request.getParameterNames();
		
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement().toString();
			paramValue = request.getParameter(paramName);
			if(null==paramValue||paramValue.trim().length()==0){
				continue;
			}
			if(null==paramName||paramName.trim().length()==0){
				continue;
			}			
			if(paramValue.equals("_")||paramName.equals("_")){
				continue;
			}
			//System.out.println(paramName+"#"+paramName);
			if(DESC_KEY.equals(paramName)){
				String s = paramValue;
				StringBuffer sb = new StringBuffer();
				for(int i=0;i<s.length();i++){
					char c = s.charAt(i);
					if(Character.isUpperCase(c)){
						sb.append("_");
					}
					sb.append(String.valueOf(c).toLowerCase());	
				}
				paramValue = sb.toString();
			}

			if (!isEmpty(paramValue)) dc.getParams().put(paramName, paramValue);
		}
		
		if (keyValues.length % 2 == 0) {
			for (int i = 0; i < keyValues.length; i+=2) {
				if (keyValues[i + 1] != null) dc.getParams().put(keyValues[i].toString(), keyValues[i + 1]);
			}
		}		
		return dc;
	}	
	
	
	
	/**
	 * 导出查询条件的数据
	 * @param request
	 * @return 分页最大数量， 查询条件
	 */
	protected DefaultCriteria makeDefaultCriteria2(long maxCount,HttpServletRequest request, Object ... keyValues) {
		String paramName = null;
		String paramValue = null;		
		DefaultCriteria dc = new DefaultCriteria(0L, maxCount);
		Enumeration<?> paramNames = request.getParameterNames();
		
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement().toString();
			paramValue = request.getParameter(paramName);
			if(null==paramValue||paramValue.trim().length()==0){
				continue;
			}
			if(null==paramName||paramName.trim().length()==0){
				continue;
			}			
			if(paramValue.equals("_")||paramName.equals("_")){
				continue;
			}
			//System.out.println(paramName+"#"+paramName);
			if(DESC_KEY.equals(paramName)){
				String s = paramValue;
				StringBuffer sb = new StringBuffer();
				for(int i=0;i<s.length();i++){
					char c = s.charAt(i);
					if(Character.isUpperCase(c)){
						sb.append("_");
					}
					sb.append(String.valueOf(c).toLowerCase());	
				}
				paramValue = sb.toString();
			}

			if (!isEmpty(paramValue)) dc.getParams().put(paramName, paramValue);
		}
		
		if (keyValues.length % 2 == 0) {
			for (int i = 0; i < keyValues.length; i+=2) {
				if (keyValues[i + 1] != null) dc.getParams().put(keyValues[i].toString(), keyValues[i + 1]);
			}
		}		
		return dc;
	}
	

	/**
	 * 设置COOKIE
	 * @param cookies
	 * @param response
	 * @param time
	 */
	protected void addCookies(List<Cookie> cookies,HttpServletResponse response,String domain,int time){
		for(Cookie cookie:cookies){
			cookie.setDomain(domain);
			cookie.setMaxAge(time);            
			cookie.setPath("/");   
			response.addCookie(cookie);
		}
	}
	
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class,new PropertyEditorSupport(){
        	@SuppressWarnings("deprecation")
			@Override
        	public void setAsText(String text) throws IllegalArgumentException {
        		if(text!=null&&text.trim().length()!=0)
        			setValue(new Date(text.replaceAll("-", "/")));
        	}
        });
//        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true));
	}
	
	protected String getRealPath(HttpServletRequest request, String path) {
		return request.getSession().getServletContext().getRealPath(path);
	}
	
}